package com.cyn.controller.login;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import io.swagger.annotations.ApiOperation;
import org.ofdrw.converter.utils.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {




    // Login form
    @RequestMapping("/login.html")
    public String login() {
        return "login.html";
    }

    // Login form with error
    @RequestMapping("/login-error.html")
    public String loginError(Model model) {
        model.addAttribute("loginError", true);
        return "login.html";
    }

    @ResponseBody
    @PostMapping({"/login"})
    @ApiOperation("登录 [测试使用]")
    public Object login(@RequestParam String username, @RequestParam String password, @RequestParam(defaultValue = "c2VydmljZToxMjM=") String clientAuth) {
        Map<String, Object> param = new HashMap();
        param.put("username", username);
        param.put("password", password);
        param.put("grant_type", "password");
        String response = null;

        try {
            HttpRequest post = ((HttpRequest) HttpUtil.createPost("http://localhost:18080/oauth/token").header("Authorization", "Basic " + clientAuth)).form(param);
            HttpResponse httpResponse = post.execute();
            response = httpResponse.body();
        } catch (RuntimeException var8) {
            response = var8.getMessage();
            if (StringUtils.isBlank(response)) {
                throw var8;
            }
        }

        return response;
    }

}
